<template>
  <view class="hxk-tree">
    <view class="hxk-tree-mask" :class="{'show':showTree}" @tap="maskClickClose"></view>
    <view class="hxk-tree-cnt" :style="{'top':topSafeArea+'px'}" :class="{'show':showTree}">
      <view class="hxk-tree-bar">
<!--        <view class="hxk-tree-bar-cancel" :style="{'color':cancelColor}" hover-class="hover-c" @tap="_cancel">取消-->
<!--        </view>-->
        <view class="hxk-tree-bar-title" :style="{'color':titleColor}">{{ title }}</view>
<!--        <view class="hxk-tree-bar-confirm" :style="{'color':confirmColor}" hover-class="hover-c" @tap="_confirm">确定-->
<!--        </view>-->
      </view>
      <view class="hxk-tree-view">
        <view class="hxk-tree-view-search">
          <u-input
              v-model="searchValue"
              placeholder="请输入关键字搜索"
              prefixIcon="search"
              prefixIconStyle="font-size: 22px;color: #909399"
              @input="handleInput"
          ></u-input>
        </view>

        <scroll-view class="hxk-tree-view-sc" :scroll-y="true">
          <block v-for="(item, index) in treeList" :key="index">
            <view class="hxk-tree-item" :style="[{
							paddingLeft: item.rank*15 + 'px',
							zIndex: item.rank*-1 +50
						}]"
                  :class="{
							border: border === true,
							show: item.show,
							last: item.lastRank,
							showchild: item.showChild,
							open: item.open,
						}">
              <view class="hxk-tree-label" @tap.stop="_treeItemTap(item, index)">
                <image class="hxk-tree-icon"
                       :src="item.lastRank ? lastIcon : item.showChild ? currentIcon : defaultIcon"></image>
                {{ item.name }}
              </view>
              <view class="hxk-tree-check" @tap.stop="_treeItemSelect(item, index)"
                    v-if="selectParent?true:item.lastRank">
                <view class="hxk-tree-check-yes" v-if="item.checked" :class="{'radio':!multiple}"
                      :style="{'border-color':confirmColor}">
                  <view class="hxk-tree-check-yes-b" :style="{'background-color':confirmColor}"></view>
                </view>
                <view class="hxk-tree-check-no" v-else :class="{'radio':!multiple}"
                      :style="{'border-color':confirmColor}"></view>
              </view>
            </view>
          </block>
          <view class="hxk-tree-view-nodata" v-if="treeList.length === 0">
            <view class="hxk-tree-view-nodata-icon"></view>
            <view class="hxk-tree-view-nodata-text">暂无数据</view>
          </view>
        </scroll-view>
        <view class="hxk-tree-view-footer">
          <view class="hxk-tree-view-footer-button" :style="{'color':cancelColor}" hover-class="hover-c" @tap="_cancel">取消
          </view>
<!--          <view class="hxk-tree-bar-title" :style="{'color':titleColor}">{{ title }}</view>-->
          <view class="hxk-tree-view-footer-button hxk-tree-view-footer-button--confirm" :style="{'color':confirmColor}" hover-class="hover-c" @tap="_confirm">确定
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>

import {debounce} from "@/utils/common";

export default {
  name: 'HxkTree',
  props: {
    //数据
    data: {
      type: Array,
      default: () => []
    },
    //唯一标识
    idKey: {
      type: String,
      default: 'id'
    },
    //名称
    nameKey: {
      type: String,
      default: 'name'
    },
    //标题
    title: {
      type: String,
      default: '请选择'
    },
    // 点击遮罩层是否关闭弹窗
    maskClick: {
      type: Boolean,
      default: true
    },
    multiple: { // 是否可以多选
      type: Boolean,
      default: false
      // default: true
    },
    selectParent: { //是否可以选父级
      type: Boolean,
      default: false
    },
    foldAll: { //折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
      type: Boolean,
      default: false
    },
    confirmColor: { // 确定按钮颜色
      type: String,
      default: '' // #07bb07
    },
    cancelColor: { // 取消按钮颜色
      type: String,
      default: '' // #757575
    },
    titleColor: { // 标题颜色
      type: String,
      default: '' // #757575
    },
    currentIcon: { // 展开时候的ic
      type: String,
      default: ''
    },
    defaultIcon: { // 折叠时候的ic
      type: String,
      default: ''
    },
    lastIcon: { // 没有子集的ic
      type: String,
      default: ''
    },
    border: { // 是否有分割线
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      // 展示文字
      textShow: '',
      //展示
      showTree: false,
      // 树形数据列表
      treeList: [],
      //选择索引
      selectIndex: -1,
      //搜素值
      searchValue: '',
      topSafeArea: 0,
    };
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        this._initTree(newVal)
      }
    }
  },
  created(){
    let app = uni.getWindowInfo();
    this.topSafeArea = app.safeAreaInsets.top + 100 //屏幕顶部安全距离
  },
  mounted() {
    this._initTree();
  },
  methods: {
    // 展示
    _show() {
      this.showTree = true
    },
    //隐藏
    _hide() {
      this.showTree = false
    },
    // 遮罩层点击
    maskClickClose() {
      console.log('maskClick', this.maskClick)
      if (this.maskClick) {
        this._cancel()
      }
    },
    // 取消
    _cancel() {
      this._hide()
      this.$emit("cancel", '');
    },
    // 确定
    _confirm() {
      // 处理所选数据
      let result = [], obj = {};
      this.treeList.forEach((item, index) => {
        if (this.treeList[index].checked) {
          obj = {}
          // obj.parents = this.treeList[index].parents
          obj = Object.assign(obj, this.treeList[index].source)
          //移除子元素
          delete obj.children
          //所有父元素
          let parentArr = this.treeList[index].parents.map(item => {
            delete item.source.children
            return {
              ...item.source,
            }
          })
          result = result.concat(parentArr)
          result.push(obj)
        }
      })
      this.textShow = result.map(item => item[this.nameKey]).join('/')

      this._hide()
      this.$emit("confirm", result);
    },

    _initTree(list = this.data) {
      this.treeList = []
      this._renderTree(list)
      this.$nextTick(() => {
        // console.log('渲染完成', this.treeList)
        this._defaultSelect(list)
      })
    },
    // 扁平化树形结构，渲染树形结构
    _renderTree(list = [], rank = 0, parentId = [], parents = []) {
      list.forEach(item => {
        this.treeList.push({
          id: item[this.idKey],//唯一标识
          name: item[this.nameKey],//名称
          source: item,
          parentId, // 父级id数组
          parents, // 父级id数组
          rank, // 层级
          // showChild: false, //子级是否显示
          showChild: item.showChild ? item.showChild : false, //子级是否显示
          // open: false, //是否打开
          open: item.open ? item.open : false, //是否打开
          show: rank === 0 || item.show, // 自身是否显示
          hideArr: [],
          orChecked: item.checked ? item.checked : false,
          checked: item.checked ? item.checked : false,
        })
        if (item.children && item.children.length > 0) {
          let parentIds = [...parentId], parentArr = [...parents], childIds = [];
          delete parentArr.children
          parentIds.push(item[this.idKey])
          parentArr.push({
            [this.idKey]: item[this.idKey],
            [this.nameKey]: item[this.nameKey],
            rank: rank,
            checked: item.checked ? item.checked : false,
            source: item,
          })
          this._renderTree(item.children, rank + 1, parentIds, parentArr)
        } else {
          this.treeList[this.treeList.length - 1].lastRank = true;
        }
      })
    },
    // 处理默认选择
    _defaultSelect() {
      this.treeList.forEach((v, i) => {
        if (v.checked) {
          this.treeList.forEach((v2, i2) => {
            if (v.parentId.toString().indexOf(v2.parentId.toString()) >= 0) {
              v2.show = true
              if (v.parentId.includes(v2.id)) {
                v2.showChild = true;
                v2.open = true;
              }
            }
          })
        }
      })
    },
    // 树形结构点击
    _treeItemTap(item, index) {
      if (item.lastRank === true) {
        //点击最后一级时触发事件
        this.treeList[index].checked = !this.treeList[index].checked
        this._fixMultiple(index)
        return;
      }
      let list = this.treeList;
      let id = item.id;
      item.showChild = !item.showChild;
      item.open = item.showChild ? true : !item.open;
      list.forEach((childItem, childIndex) => {
        if (item.showChild === false) {
          // 隐藏所有子级
          if (!childItem.parentId.includes(id)) {
            return;
          }
          if (!this.foldAll) {
            if (childItem.lastRank !== true && !childItem.open) {
              childItem.showChild = false;
            }
            // 为隐藏的内容添加一个标记
            if (childItem.show) {
              childItem.hideArr[item.rank] = id
            }
          } else {
            if (childItem.lastRank !== true) {
              childItem.showChild = false;
            }
          }
          childItem.show = false;
        } else {
          // 打开子集
          if (childItem.parentId[childItem.parentId.length - 1] === id) {
            childItem.show = true;
          }
          // 打开被隐藏的子集
          if (childItem.parentId.includes(id) && !this.foldAll) {
            if (childItem.hideArr[item.rank] === id) {
              childItem.show = true;
              if (childItem.open && childItem.showChild) {
                childItem.showChild = true
              } else {
                childItem.showChild = false
              }
              childItem.hideArr[item.rank] = null
            }
          }
        }
      });
    },
    // 树形结构选择
    _treeItemSelect(item, index) {
      this.treeList[index].checked = !this.treeList[index].checked
      this._fixMultiple(index)
    },
    // 处理单选多选
    _fixMultiple(index) {
      if (!this.multiple) {
        // 如果是单选
        this.treeList.forEach((v, i) => {
          if (i != index) {
            this.treeList[i].checked = false
          } else {
            this.treeList[i].checked = true
          }
        })
      }
    },
    handleInput: debounce(function () {
      console.log(this.searchValue)
      let data = JSON.parse(JSON.stringify(this.data))
      let resultTree = this.filterTree(this.searchValue, data)
      this._initTree(resultTree)
      console.log(resultTree)
    }, 500),
    // 筛选树形结构
    filterTree(value, tree = this.data, result = []) {
      //
      if (!(tree.length && value)) {
        return tree
      }
      for (let item of tree) {
        // 匹配到关键字
        if (item[this.nameKey].indexOf(value) >= 0) {
          item['show'] = true
          result.push(item)
          continue;
        }
        if (item.children && item.children.length > 0) {
          let children = this.filterTree(value, item.children, [])
          if (children.length > 0) {
            item.children = children
            item['showChild'] = true
            item['open'] = true
            item['show'] = true
            result.push(item)
          }
        }
      }
      return result
    },
    //清空外层展示的输入框内容
    clearTextShow() {
      this.textShow = ''
      this._initTree()
    }
  }
};
</script>

<style lang="scss" scoped>
.hxk-tree{
  width: 100%;
}
.hxk-tree-mask {
  position: fixed;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 9998;
  background-color: rgba(0, 0, 0, 0.6);
  opacity: 0;
  transition: all 0.3s ease;
  visibility: hidden;
}

.hxk-tree-mask.show {
  visibility: visible;
  opacity: 1;
}

.hxk-tree-cnt {
  position: fixed;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 9999;
  top: 160rpx;
  transition: all 0.3s ease;
  transform: translateY(100%);
}

.hxk-tree-cnt.show {
  transform: translateY(0);
}

.hxk-tree-bar {
  background-color: #fff;
  height: 72rpx;
  padding-left: 20rpx;
  padding-right: 20rpx;
  display: flex;
  //justify-content: space-between;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  border-bottom-width: 1rpx !important;
  border-bottom-style: solid;
  border-bottom-color: #f5f5f5;
  font-size: 32rpx;
  color: #757575;
  line-height: 1;
}

.hxk-tree-bar-title {
  display: flex;
  height: 100%;
  font-size: 26rpx;
  font-weight: 600;
  align-items: center;
}

.hxk-tree-bar-confirm {
  color: $hxk-primary-color;
}

.hxk-tree-view {
  position: absolute;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  top: 72rpx;
  background-color: #fff;
  padding-top: 20rpx;
  padding-right: 20rpx;
  padding-bottom: 20rpx;
  padding-left: 20rpx;

  .hxk-tree-view-search {
    height: 80rpx;
    display: flex;
  }

  .hxk-tree-view-footer{
    height: 100rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx;
    .hxk-tree-view-footer-button{
      height: 60rpx;
      width: 311rpx;
      background-color: #fff;
      text-align: center;
      border: 1rpx solid #e5e5e5;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 10rpx;
      &--confirm{
        background-color: $hxk-primary-color;
        color: #fff;
        border-color: $hxk-primary-color;
      }
    }
  }
}

.hxk-tree-view-sc {
  //height: calc(100% - 80rpx);
  height: calc(100% - 180rpx);
  overflow: hidden;
}

.hxk-tree-view-nodata {
  padding: 20rpx;
  text-align: center;
}

.hxk-tree-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 26rpx;
  color: #757575;
  line-height: 1;
  height: 0;
  opacity: 0;
  transition: 0.2s;
  position: relative;
  overflow: hidden;
}

.hxk-tree-item.show {
  height: 80rpx;
  opacity: 1;
}

.hxk-tree-item.showchild:before {
  transform: rotate(90deg);
}

.hxk-tree-item.last:before {
  opacity: 0;
}

.hxk-tree-icon {
  width: 26rpx;
  height: 26rpx;
  margin-right: 8rpx;
}

.hxk-tree-label {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
  line-height: 1.2;
}

.hxk-tree-check {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hxk-tree-check-yes,
.hxk-tree-check-no {
  width: 20px;
  height: 20px;
  border-top-left-radius: 20%;
  border-top-right-radius: 20%;
  border-bottom-right-radius: 20%;
  border-bottom-left-radius: 20%;
  border-top-width: 1rpx;
  border-left-width: 1rpx;
  border-bottom-width: 1rpx;
  border-right-width: 1rpx;
  border-style: solid;
  border-color: $hxk-primary-color;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.hxk-tree-check-yes-b {
  width: 12px;
  height: 12px;
  border-top-left-radius: 20%;
  border-top-right-radius: 20%;
  border-bottom-right-radius: 20%;
  border-bottom-left-radius: 20%;
  background-color: $hxk-primary-color;
}

.hxk-tree-check .radio {
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}

.hxk-tree-check .radio .hxk-tree-check-yes-b {
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}

.hover-c {
  opacity: 0.6;
}

</style>